package me.ingxin.android.permission2.request

import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentManager

/**
 * Created on 2023/7/2 by yin
 * 任务链
 * @param taskList 任务列表
 * @param index 待执行任务索引
 */
internal class TaskChain(
    val context: Context,
    val fragmentManager: FragmentManager,
    private val taskList: List<Task>,
    private val index: Int
) {

    private fun copy(index: Int) = TaskChain(context, fragmentManager, taskList, index)

    /**
     * 继续执行任务链中的任务
     * @param request 执行任务参数
     */
    fun proceed(request: Request) {
        if (index >= taskList.size) {
            //达到任务链末端
            return
        }
        val next = copy(index + 1)
        val task = taskList[index]
        task.runTask(next, request)
    }

    /**
     * 从任务链头部开始执行
     */
    fun proceedHead(request: Request) {
        var position = index
        if (index >= taskList.size) {
            position = taskList.size - 1
        }
        Log.w("TaskChain", "task chain proceedHead by ${taskList[position].javaClass.name}")

        val next = copy(1)
        val task = taskList[0]
        task.runTask(next, request)
    }

}